/*******************************************************************************
 * Copyright (c) 2013 Prometheus Consulting
 *
 *     Licensed under the Apache License, Version 2.0 (the "License"); you may
 *     not use this file except in compliance with the License. You may obtain
 *     a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *     WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *     License for the specific language governing permissions and limitations
 *     under the License.
 *******************************************************************************/
package nz.co.senanque.pizzaordermobile;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nz.co.senanque.pizzaorder.instances.OrderItem;
import nz.co.senanque.pizzaorder.instances.Pizza;
import nz.co.senanque.vaadinsupport.MaduraPropertyWrapper;
import nz.co.senanque.vaadinsupport.SimpleButtonPainter;
import nz.co.senanque.vaadinsupport.SubmitButtonPainter;
import nz.co.senanque.vaadinsupport.application.MaduraSessionManager;
import nz.co.senanque.vaadinsupport.application.SpringApplicationLoader;
import nz.co.senanque.vaadinsupport.viewmanager.TouchLoginForm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;

import com.vaadin.addon.touchkit.ui.HorizontalComponentGroup;
import com.vaadin.addon.touchkit.ui.TouchKitApplication;
import com.vaadin.addon.touchkit.ui.TouchKitWindow;
import com.vaadin.addon.touchkit.ui.VerticalComponentGroup;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Window;

public class PizzaorderMobile extends TouchKitApplication  implements MessageSourceAware {

	protected transient Logger log = LoggerFactory.getLogger(this.getClass());
	private MessageSourceAccessor m_messageSourceAccessor;
    private HttpServletRequest m_currentRequest;
    private Window m_mainWindow;
	@Autowired private MaduraSessionManager m_maduraSessionManager;
	@Autowired private ProductForm productForm;
	@Autowired private TouchLoginForm m_loginForm;

    @Override
    public String getVersion()
    {
    	return m_messageSourceAccessor.getMessage("version", null,"NOVERSION");
    }
    @Override
    public void init() {
        if (m_messageSourceAccessor != null)
        {
        	throw new IllegalStateException("context already loaded");
        }
        if (m_currentRequest == null)
        {
        	throw new IllegalStateException("no current request");
        }
        SpringApplicationLoader.loadContext(this, m_currentRequest);   	
        m_mainWindow = new TouchKitWindow();
        m_mainWindow.setImmediate(true);
		setMainWindow(m_mainWindow);
    }
    @Override
    public void onBrowserDetailsReady() {
		
		final CssLayout content = new CssLayout();
		content.setWidth("100%");
		
		// do not addComponent() here because the window is created with an internal VerticalLayout 
		// which won't render under touchkit unless overridden by the setContent()
		m_mainWindow.setContent(content);
		content.removeAllComponents();
		
		// Set up the login page for initial display
		VerticalComponentGroup componentGroup1 = new VerticalComponentGroup();
		componentGroup1.setCaption(m_messageSourceAccessor.getMessage("welcome"));
		content.addComponent(componentGroup1);
		componentGroup1.addComponent(m_loginForm);

		// This listener will be fired when the username changes, ie when we log in.
		this.addListener(new UserChangeListener(){

			public void applicationUserChanged(UserChangeEvent event) {
				content.removeAllComponents();
				VerticalComponentGroup componentGroup = new VerticalComponentGroup();
				componentGroup.setCaption(m_messageSourceAccessor.getMessage("title"));
				content.addComponent(componentGroup);
				
		        final MaduraSessionManager maduraSessionManager = getMaduraSessionManager();
		        final Pizza pizza = new Pizza();
		        maduraSessionManager.getValidationSession().bind(pizza);
		        productForm.setItemDataSource(new BeanItem<OrderItem>(pizza));
				final List<MaduraPropertyWrapper> properties = productForm.getItemDataSourceProperties();
		        Button orderButton = new Button();
		        orderButton.setCaption("logout");
		        Button resetButton = new Button();
		        resetButton.setCaption("resetButton");
		        resetButton.addListener(new ClickListener(){

					public void buttonClick(ClickEvent event) {
						// We only need to reset two fields for everything to go back to the start.
						for (MaduraPropertyWrapper wrapper: properties)
						{
							if (wrapper.getName().equals("size"))
							{
								wrapper.setValue(null);
							}
							if (wrapper.getName().equals("topping"))
							{
								wrapper.setValue(null);
							}
						}
						maduraSessionManager.updateOtherFields(null);
					}});
		        orderButton.addListener(new ClickListener(){

					public void buttonClick(ClickEvent event) {
						TouchKitApplication.get().close(); // Ends the application. We don't save it to the order.
					}});
				componentGroup.addComponent(productForm);
				maduraSessionManager.register(orderButton, new SubmitButtonPainter(m_maduraSessionManager));
				maduraSessionManager.bind(orderButton, properties);
				maduraSessionManager.register(resetButton, new SimpleButtonPainter(m_maduraSessionManager));
				maduraSessionManager.bind(resetButton, properties);
				
				HorizontalComponentGroup horizontalComponentGroup = new HorizontalComponentGroup();
				horizontalComponentGroup.setMargin(true);
				horizontalComponentGroup.addComponent(orderButton);
				horizontalComponentGroup.addComponent(resetButton);
				componentGroup.addComponent(horizontalComponentGroup);
				
			}});
	}

	@Override
	public void onRequestStart(HttpServletRequest request,
			HttpServletResponse response) {
		super.onRequestStart(request, response);
		m_currentRequest = request;
	}

	public void setMessageSource(MessageSource messageSource) {
		m_messageSourceAccessor = new MessageSourceAccessor(messageSource);
	}

	protected MaduraSessionManager getMaduraSessionManager() {
		return m_maduraSessionManager;
	}

	protected void setMaduraSessionManager(MaduraSessionManager maduraSessionManager) {
		m_maduraSessionManager = maduraSessionManager;
	}

	protected ProductForm getProductForm() {
		return productForm;
	}

	protected void setProductForm(ProductForm productForm) {
		this.productForm = productForm;
	}

	protected TouchLoginForm getLoginForm() {
		return m_loginForm;
	}

	protected void setLoginForm(TouchLoginForm loginForm) {
		m_loginForm = loginForm;
	}

}
